package com.itmck.init;

import com.baomidou.mybatisplus.extension.conditions.query.LambdaQueryChainWrapper;
import com.itmck.pojo.UserInfo;
import com.itmck.dao.SpringSecurityUserMapper;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Component;

import javax.annotation.PostConstruct;
import javax.annotation.Resource;

/**
 * 太阳当空照,花儿对我笑
 * <p>
 * Create by M ChangKe 2021/11/19 10:45
 **/
@Component
public class UserDataInit {

    @Resource
    private SpringSecurityUserMapper springSecurityUserMapper;

    @Resource
    private PasswordEncoder passwordEncoder;

    @PostConstruct
    public void init() {

        UserInfo admin = new UserInfo();
        admin.setUsername("admin");
        admin.setPassword(passwordEncoder.encode("123"));
        admin.setRole("admin,normal");
        insertUserInfo(admin, "admin");


        UserInfo user = new UserInfo();
        user.setUsername("user");
        user.setPassword(passwordEncoder.encode("123"));
        user.setRole("normal");
        insertUserInfo(user, "user");
    }

    private void insertUserInfo(UserInfo admin, String username) {
        UserInfo userInfo = new LambdaQueryChainWrapper<>(springSecurityUserMapper)
                .eq(UserInfo::getUsername, username)
                .one();
        if (userInfo == null) {
            springSecurityUserMapper.insert(admin);
        }
    }
}